#!/bin/sh

# 用硬链接备份文件系统

hash_file () {
	FILE=$1
	DESTINATION=$2
	SHA1SUM=`sha1sum ${FILE}|cut -d' ' -f1`
	DIRECTORY=${DESTINATION}/${SHA1SUM}
	mkdir -p ${DIRECTORY}
	if [ ! -f ${DIRECTORY}/${FILE} ]; then
		echo "hash_file: ${FILE} ${DESTINATION}"
		ln ${FILE} ${DIRECTORY}/${FILE} 
	fi
}

hash_repo () {
	SOURCE=$1
	DESTINATION=$2
	if [ -d ${SOURCE}/.git ]; then
		HASH=$(git --work-tree=${SOURCE} --git-dir=${SOURCE}/.git log --oneline|tail -n1|cut -d' ' -f1)
		DIRECTORY=${DESTINATION}/${HASH}
		mkdir -p ${DIRECTORY}
		echo "hash_repo: ${SOURCE} ${DESTINATION}"
		ln -s ${SOURCE} ${DIRECTORY}
	fi
}

hash_recursive () {
	SOURCE=$1
	DESTINATION=$2
	for item in `ls ${SOURCE}`;
	do
		echo "hash_recursive: ${SOURCE} ${DESTINATION} | ${item}"
		if [ -f ${SOURCE}/${item} ]; then
			hash_file ${SOURCE}/${item} ${DESTINATION}/files
		fi
		if [ -d ${SOURCE}/${item} ]; then
			if [ -d ${SOURCE}/${item}/.git ]; then
				hash_repo ${SOURCE}/${item} ${DESTINATION}/repositories
			else
				hash_recursive ${SOURCE}/${item} ${DESTINATION}
			fi
		fi
	done
}


hash_recursive $1 $2
